using System;
using System.Collections.Generic;
using System.Text;
using log4net.Layout;
using log4net.Core;
using log4net.Util;
using System.Net;
using System.Net.Sockets;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Threading;
using System.Net.NetworkInformation;
using System.Diagnostics;

using DNSharp;

namespace Splunk.Extensions
{
    /// <summary>
    /// UDP Based splunk appender
    /// </summary>
    public class SplunkUDPAppender : BaseDNSAppender 
    {
        /// <summary>
        /// .ctor
        /// </summary>
        public SplunkUDPAppender()
            : base(LoadBalanceMode.Persistent)
        {

        }

        /// <summary>
        /// Maximum size for the buffer.
        /// </summary>
        const int MAXBUFFER = 1492;
        const SocketFlags SENDFLAGS = SocketFlags.None;
        private Socket _Socket = null;

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        protected override bool Initialize()
        {
            try
            {
                if (LogLog.IsDebugEnabled) LogLog.Debug(
                    string.Format("SplunkUDPAppender:Initializing Socket...")
                    );
                _Socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                return true;
            }
            catch (Exception ex)
            {
                if (LogLog.IsErrorEnabled)
                    LogLog.Error("SplunkUDPAppender:Exception thrown during Initialize", ex);
                return false;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="message"></param>
        protected override void SendMessage(byte[] message)
        {
            IPEndPoint endPoint = GetEndPoint();
            int length = message.Length > MAXBUFFER ? MAXBUFFER : message.Length;
            _Socket.SendTo(message, 0, length, SocketFlags.None, endPoint);
        }
        
    }
}
